<template>
  <div class="p-6 space-y-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
    <!-- 页面标题和操作按钮 -->
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
      <h2 class="text-2xl font-bold text-gray-900 dark:text-gray-100 flex items-center gap-2">
        <svg class="w-6 h-6 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
        </svg>
        用户管理
      </h2>
      <div class="flex flex-wrap gap-3">
        <el-button
          @click="showAddDialog = true"
          type="primary"
          icon="Plus"
          class="flex items-center gap-2 shadow-md transition-all hover:shadow-lg">
          新增用户
        </el-button>
        <el-button
          @click="handleImport"
          type="default"
          icon="Upload"
          class="flex items-center gap-2 shadow-md transition-all hover:shadow-lg">
          导入
        </el-button>
        <el-button
          @click="handleExport"
          type="default"
          icon="Download"
          class="flex items-center gap-2 shadow-md transition-all hover:shadow-lg">
          导出
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选表单 -->
    <div class="card p-6 bg-white dark:bg-gray-800 rounded-xl shadow-md">
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">用户名</label>
          <input v-model="searchForm.username" type="text" placeholder="输入用户名" class="input w-full" />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">邮箱</label>
          <input v-model="searchForm.email" type="email" placeholder="输入邮箱" class="input w-full" />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">角色</label>
          <select v-model="searchForm.role" class="input w-full">
            <option value="">全部角色</option>
            <option value="管理员">管理员</option>
            <option value="普通用户">普通用户</option>
            <option value="编辑者">编辑者</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">状态</label>
          <select v-model="searchForm.status" class="input w-full">
            <option value="">全部状态</option>
            <option value="active">正常</option>
            <option value="inactive">禁用</option>
          </select>
        </div>
      </div>
      <div class="flex flex-wrap gap-3 justify-end">
        <el-button @click="resetSearch" type="default" class="shadow-sm">重置</el-button>
        <el-button @click="searchUsers" type="primary" class="shadow-sm">搜索</el-button>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="card bg-white dark:bg-gray-800 rounded-xl shadow-md overflow-hidden">
      <el-table v-loading="loading" :data="users" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="用户信息" width="300">
          <template #default="{ row }">
            <div class="flex items-center gap-3">
              <img
                :src="row.avatar"
                :alt="row.username"
                class="w-10 h-10 rounded-full border-2 border-gray-200 dark:border-gray-700" />
              <div>
                <p class="font-medium text-gray-900 dark:text-gray-100">{{ row.username }}</p>
                <p class="text-sm text-gray-600 dark:text-gray-400">{{ row.email }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" width="120" />
        <el-table-column prop="department" label="部门" width="150" />
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <span
              :class="[
                'px-2 py-1 text-sm rounded-full',
                row.status === 'active'
                  ? 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200'
                  : 'bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200',
              ]">
              {{ row.status === 'active' ? '正常' : '禁用' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="lastLogin" label="最后登录" width="180" />
        <el-table-column label="操作" min-width="220" fixed="right">
          <template #default="{ row }">
            <div class="flex items-center gap-2">
              <el-button @click="editUser(row)" type="default" size="small"> 编辑 </el-button>
              <el-button
                @click="toggleUserStatus(row)"
                :type="row.status === 'active' ? 'danger' : 'success'"
                size="small">
                {{ row.status === 'active' ? '禁用' : '启用' }}
              </el-button>
              <el-button @click="deleteUser(row)" type="danger" size="small" :disabled="row.id === 1">
                <!-- 防止删除管理员 -->
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- Element Plus 分页 -->
      <div
        class="flex justify-between items-center p-4 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50">
        <div class="text-sm text-gray-600 dark:text-gray-400">
          共 {{ totalUsers }} 条记录，当前显示 {{ (currentPage - 1) * pageSize + 1 }} 至
          {{ Math.min(currentPage * pageSize, totalUsers) }} 条
        </div>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalUsers"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="custom-pagination" />
      </div>
    </div>

    <!-- 新增/编辑用户弹窗 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingUser ? '编辑用户' : '新增用户'"
      width="500px"
      :before-close="handleDialogClose">
      <form @submit.prevent="saveUser" class="space-y-6 p-2">
        <div class="grid grid-cols-1 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
              >用户名 <span class="text-red-500">*</span></label
            >
            <input v-model="userForm.username" type="text" class="input w-full" required placeholder="请输入用户名" />
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
              >邮箱 <span class="text-red-500">*</span></label
            >
            <input v-model="userForm.email" type="email" class="input w-full" required placeholder="请输入邮箱" />
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
              >角色 <span class="text-red-500">*</span></label
            >
            <select v-model="userForm.role" class="input w-full" required>
              <option value="">请选择角色</option>
              <option value="管理员">管理员</option>
              <option value="普通用户">普通用户</option>
              <option value="编辑者">编辑者</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">部门</label>
            <input v-model="userForm.department" type="text" class="input w-full" placeholder="请输入部门" />
          </div>
          <div v-if="!editingUser">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
              >密码 <span class="text-red-500">*</span></label
            >
            <input v-model="userForm.password" type="password" class="input w-full" required placeholder="请输入密码" />
          </div>
        </div>
      </form>
      <template #footer>
        <div class="flex justify-end gap-3">
          <el-button @click="showAddDialog = false" type="default">取消</el-button>
          <el-button @click="saveUser" type="primary" :loading="saving">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="system-user">
import { ref, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { getUsersApi, createUserApi, updateUserApi, deleteUserApi, toggleUserStatusApi } from '@/api/user'

defineOptions({ name: 'user' })

// 搜索表单
const searchForm = ref<{ username: string; email: string; role: string; status: string }>({
  username: '',
  email: '',
  role: '',
  status: '',
})

const showAddDialog = ref(false)
const editingUser = ref<any>(null)
const currentPage = ref(1)
const pageSize = ref(10)
const totalUsers = ref(100)
const loading = ref(false)
const saving = ref(false)

const userForm = ref<{ username: string; email: string; role: string; department: string; password?: string }>({
  username: '',
  email: '',
  role: '',
  department: '',
  password: '',
})

// 用户数据
const users = ref<any[]>([])

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const res = await getUsersApi({
      page: currentPage.value,
      pageSize: pageSize.value,
      username: searchForm.value.username,
      email: searchForm.value.email,
      role: searchForm.value.role,
      status: searchForm.value.status,
    })
    users.value = res.data || []
    totalUsers.value = res.total || 0
  } catch (error) {
    ElMessage({
      message: '获取用户列表失败: ' + (error as any).message,
      type: 'error',
    })
  } finally {
    loading.value = false
  }
}

// 搜索用户
function searchUsers() {
  currentPage.value = 1 // 搜索后重置到第一页
  fetchUsers()
}

// 重置搜索
function resetSearch() {
  searchForm.value = {
    username: '',
    email: '',
    role: '',
    status: '',
  }
  currentPage.value = 1
  fetchUsers()
}

// 编辑用户
function editUser(user: any) {
  editingUser.value = { ...user }
  userForm.value = {
    username: user.username,
    email: user.email,
    role: user.role,
    department: user.department,
  }
  showAddDialog.value = true
}

// 保存用户
async function saveUser() {
  // 表单验证
  if (!userForm.value.username || !userForm.value.email || !userForm.value.role) {
    ElMessage({
      message: '请填写必填字段',
      type: 'error',
    })
    return
  }

  saving.value = true

  try {
    if (editingUser.value) {
      // 更新用户
      await updateUserApi(editingUser.value.id, userForm.value)
      ElMessage({ message: '用户更新成功', type: 'success' })
    } else {
      // 新增用户
      await createUserApi(userForm.value)
      ElMessage({ message: '用户创建成功', type: 'success' })
    }

    showAddDialog.value = false
    editingUser.value = null
    userForm.value = {
      username: '',
      email: '',
      role: '',
      department: '',
      password: '',
    }
    fetchUsers() // 重新获取用户列表
  } catch (error) {
    ElMessage({
      message: '操作失败: ' + (error as any).message,
      type: 'error',
    })
  } finally {
    saving.value = false
  }
}

// 切换用户状态
async function toggleUserStatus(user: any) {
  const newStatus = user.status === 'active' ? 'inactive' : 'active'
  try {
    await toggleUserStatusApi(user.id, newStatus)
    user.status = newStatus
    ElMessage({ message: `用户${newStatus === 'active' ? '启用' : '禁用'}成功`, type: 'success' })
  } catch (error) {
    ElMessage({
      message: '操作失败: ' + (error as any).message,
      type: 'error',
    })
  }
}

// 删除用户
async function deleteUser(user: any) {
  if (user.id === 1) {
    ElMessage({ message: '不能删除管理员账户', type: 'error' })
    return
  }

  ElMessage({
    message: '确定要删除这个用户吗？',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async (res) => {
    if (res.confirm) {
      try {
        await deleteUserApi(user.id)
        ElMessage({ message: '用户删除成功', type: 'success' })
        fetchUsers() // 重新获取用户列表
      } catch (error) {
        ElMessage({
          message: '删除失败: ' + (error as any).message,
          type: 'error',
        })
      }
    }
  })
}

// 处理分页大小变化
function handleSizeChange(size: number) {
  pageSize.value = size
  currentPage.value = 1
  fetchUsers()
}

// 处理当前页变化
function handleCurrentChange(page: number) {
  currentPage.value = page
  fetchUsers()
}

// 处理导入
function handleImport() {
  ElMessage({ message: '导入功能开发中', type: 'info' })
}

// 处理导出
function handleExport() {
  ElMessage({ message: '导出功能开发中', type: 'info' })
}

// 处理对话框关闭
function handleDialogClose() {
  // 重置表单
  userForm.value = {
    username: '',
    email: '',
    role: '',
    department: '',
    password: '',
  }
  editingUser.value = null
  saving.value = false
}

// 初始加载数据
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped></style>
